<?php
namespace app\admin\model;

use think\Model;
use app\admin\model\user\money\Log as UserMoneyLog;
use app\admin\model\dividend\pool\Log as DividendPoolLog;

class DividendPool extends Model
{
    protected $name = 'dividend_pool';

    // 获取第一条记录
    public function getFirst()
    {
        return $this->where('id', 1)->find();
    }

    // 获取当前余额
    public function getBalance()
    {
        $balance = $this->where('id', 1)->value('balance');
        return $balance !== null ? $balance : 0;
    }

    // 扣除分红池金额
    public function deduct($amount, $orderId = null, $batchId = null, $memo = '')
    {
        $currentBalance = $this->getBalance();
        $newBalance = $currentBalance - $amount;
        
        $record = $this->where('id', 1)->find();
        // 更新减去分红池金额
        $this->where('id', 1)->update(['balance' => $newBalance]);

        // 记录分红池变动日志
        $this->recordPoolLog([
            'order_id' => $orderId,
            'batch_id' => $batchId,
            'bian_type' => '减少',
            'money' => $amount,
            'bian_money' => -$amount,
            'before' => $currentBalance,
            'after' => $newBalance,
            'memo' => $memo ?: '分红池扣除（返利支出）'
        ]);
    }

    /**
     * 触发返利时 扣除分红池 并更新资金池和新增利润
     */
    public function chufa_deduct($amount, $orderId = null, $batchId = null, $memo = '', $zijin_pool=null)
    {
        $currentBalance = $this->getBalance();
        $newBalance = $currentBalance - $amount;
        
        $record = $this->where('id', 1)->find();
        $period_after = $record->period + 1;
        // 更新减去分红池金额，资金池更新增加利润的金额，新增利润清零
        $this->where('id', 1)->update([
            'balance' => $newBalance,
            'zijin_pool' => $zijin_pool,
            'newprofit' => 0,
            'period' => $period_after,
        ]);

        // 记录分红池变动日志
        $this->recordPoolLog([
            'order_id' => $orderId,
            'batch_id' => $batchId,
            'bian_type' => '减少',
            'money' => $amount,
            'bian_money' => -$amount,
            'before' => $currentBalance,
            'after' => $newBalance,
            'memo' => $memo ?: '分红池扣除（返利支出）'
        ]);
    }

    // 添加分红池余额
    public function addBalance($amount, $orderId = null, $batchId = null, $memo = '')
    {
        $currentBalance = $this->getBalance();
        $newBalance = $currentBalance + $amount;
        
        // 如果不存在记录，则创建一个
        $record = $this->where('id', 1)->find();
        if (!$record) {
            $this->save(['id' => 1, 'balance' => $newBalance]);
        } else {
            $this->where('id', 1)->update(['balance' => $newBalance]);
        }

        // 记录分红池变动日志
        $this->recordPoolLog([
            'order_id' => $orderId,
            'batch_id' => $batchId,
            'bian_type' => '增加',
            'money' => $amount,
            'bian_money' => '+'.$amount,
            'before' => $currentBalance,
            'after' => $newBalance,
            'memo' => $memo ?: '分红池增加（订单利润注入）'
        ]);
    }

    /**
     * 记录分红池变动日志
     * @param array $data 日志数据
     */
    private function recordPoolLog($data)
    {
        DividendPoolLog::create([
            'order_id' => $data['order_id'] ?: 0,
            'batch_id' => $data['batch_id'] ?: 0,
            'type' => 'equity_value',
            'bian_type' => $data['bian_type'],
            'money' => $data['money'],
            'bian_money' => $data['bian_money'],
            'before' => $data['before'],
            'after' => $data['after'],
            'memo' => $data['memo'],
            'createtime' => time()
        ]);
    }
}